package com.example.consumer.controller;


import com.example.consumer.client.RpcClient;
import com.example.consumer.proxy.RpcClientProxy;
import com.example.rpc.api.IUserService;
import com.example.rpc.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * 当客户端发起调用，判断服务端是否全部下线
 * 每次都选择最后一次响应时间短的服务端进行服务调用，
 * 如果时间一致，随机选取一个服务端进行调用
 *
 * @author kangshuai
 */
@RestController
public class UserController {

    @GetMapping("/user/{id}")
    public Object getUserById(@PathVariable("id") Integer id) {
        int size = RpcClientProxy.list.size();
        if (size == 0) {
            throw new RuntimeException("服务端已全部下线");
        }
        User user = null;
        if (size == 1) {
            IUserService userService = (IUserService) RpcClientProxy.createProxy(IUserService.class, 0);
            user = userService.getById(id);
        } else {
            RpcClient rpcClient1 = RpcClientProxy.list.get(0);
            RpcClient rpcClient2 = RpcClientProxy.list.get(1);

            if (rpcClient1.getCostTime() < rpcClient2.getCostTime()) {
                IUserService userService = (IUserService) RpcClientProxy.createProxy(IUserService.class, 0);
                user = userService.getById(id);
            } else if (rpcClient1.getCostTime() == rpcClient2.getCostTime()) {
                Random random = new Random();
                IUserService userService = (IUserService) RpcClientProxy.createProxy(IUserService.class, random.nextInt(2));
                user = userService.getById(id);
            } else {
                IUserService userService = (IUserService) RpcClientProxy.createProxy(IUserService.class, 1);
                user = userService.getById(id);
            }
        }
        return user;
    }
}
